import Vue from 'vue'
import Vuex from 'vuex'
import {
	autoLogin
} from '../../common/tools/util.js'
// import { login } from '../../api/user.js'
Vue.use(Vuex)

const state = {
	token: uni.getStorageSync('token'),
	userInfo: uni.getStorageSync('userInfo'),
	code: uni.getStorageSync('code'),
	isIphoneX: uni.getStorageSync('isIphoneX')
};

const mutations = {
	SET_TOKEN: (state, token) => {
		uni.setStorageSync('token', token);
		state.token = token;
	},
	SET_CODE: (state, code) => {
		uni.setStorageSync('code', code);
		state.code = code;
	},
	SET_PHONE_NUMBER: (state, telephone) => {
		const userInfo = Object.assign(state.userInfo, {
			telephone: telephone
		});
		uni.setStorageSync('userInfo', userInfo);
		state.userInfo = userInfo;
	},
	SET_USER: (state, userInfo) => {
		uni.setStorageSync('userInfo', userInfo);
		state.userInfo = userInfo;
	},
	SET_IS_IPHONEX: (state, isIphoneX) => {
		uni.setStorageSync('isIphoneX', isIphoneX);
		state.isIphoneX = isIphoneX;
	}
};

const actions = {
	authLogin(login_type) {
		return new Promise((reslove, reject) => {
			autoLogin().then(userInfo => {
				if (login_type !== undefined) userInfo.login_type = 'routine';
				login(userInfo).then(res => {
					commit('SET_TOKEN')
					commit('SET_USER')
					reslove();
				}).catch(err => {
					reject();
				});
			}).catch(err => {
				reject();
			});
		})
	}
}

export default {
	namespaced: true,
	state,
	actions,
	mutations
}
